<template>
  <div class="dashboard-container">
    <!-- 顶部欢迎区域 -->
    <div class="dashboard-header">
      <div class="welcome-section">
        <div class="user-avatar">
          <el-avatar :size="80" :src="userStore.userAvatar">
            {{ userStore.userName?.charAt(0) }}
          </el-avatar>
          <div class="online-status"></div>
        </div>
        <div class="welcome-content">
          <h1>{{ getGreeting() }}，{{ userStore.userName }}！</h1>
          <p>今天也要加油学习哦～ 已连续学习 {{ consecutiveDays }} 天</p>
          <div class="quick-actions">
            <el-button type="primary" @click="goToLearning">
              <el-icon><VideoPlay /></el-icon>
              继续学习
            </el-button>
            <el-button @click="goToExam">
              <el-icon><EditPen /></el-icon>
              参加考试
            </el-button>
            <el-button @click="goToCoding">
              <el-icon><Monitor /></el-icon>
              编程练习
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="weather-widget">
        <div class="weather-info">
          <el-icon class="weather-icon"><Sunny /></el-icon>
          <div class="weather-details">
            <div class="temperature">22°C</div>
            <div class="weather-desc">晴朗</div>
          </div>
        </div>
        <div class="date-info">
          <div class="date">{{ currentDate }}</div>
          <div class="time">{{ currentTime }}</div>
        </div>
      </div>
    </div>

    <!-- 学习统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon study">
          <el-icon><Reading /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ learningStats.totalHours }}</div>
          <div class="stat-label">学习时长(小时)</div>
          <div class="stat-trend up">
            <el-icon><TrendCharts /></el-icon>
            +12% 本周
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon course">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ learningStats.completedCourses }}</div>
          <div class="stat-label">完成课程</div>
          <div class="stat-trend up">
            <el-icon><TrendCharts /></el-icon>
            +3 本月
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon exam">
          <el-icon><Trophy /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ learningStats.examScore }}</div>
          <div class="stat-label">平均分数</div>
          <div class="stat-trend up">
            <el-icon><TrendCharts /></el-icon>
            +5分 本月
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon rank">
          <el-icon><Medal /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ learningStats.ranking }}</div>
          <div class="stat-label">学习排名</div>
          <div class="stat-trend up">
            <el-icon><TrendCharts /></el-icon>
            ↑15 本周
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="dashboard-main">
      <!-- 左侧内容 -->
      <div class="main-left">
        <!-- 学习进度 -->
        <div class="dashboard-card">
          <div class="card-header">
            <h3>学习进度</h3>
            <el-button text @click="viewAllProgress">查看全部</el-button>
          </div>
          <div class="progress-list">
            <div 
              v-for="course in currentCourses" 
              :key="course.id"
              class="progress-item"
              @click="continueCourse(course)"
            >
              <div class="course-cover">
                <img :src="course.cover" :alt="course.title" />
                <div class="play-overlay">
                  <el-icon><VideoPlay /></el-icon>
                </div>
              </div>
              <div class="course-info">
                <h4>{{ course.title }}</h4>
                <p>{{ course.instructor }}</p>
                <div class="progress-bar">
                  <el-progress 
                    :percentage="course.progress" 
                    :show-text="false"
                    :stroke-width="6"
                  />
                  <span class="progress-text">{{ course.progress }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 学习计划 -->
        <div class="dashboard-card">
          <div class="card-header">
            <h3>今日学习计划</h3>
            <el-button text @click="managePlans">管理计划</el-button>
          </div>
          <div class="plan-list">
            <div 
              v-for="plan in todayPlans" 
              :key="plan.id"
              class="plan-item"
              :class="{ completed: plan.completed }"
            >
              <el-checkbox 
                v-model="plan.completed" 
                @change="updatePlanStatus(plan)"
              />
              <div class="plan-content">
                <div class="plan-title">{{ plan.title }}</div>
                <div class="plan-meta">
                  <span class="plan-time">{{ plan.estimatedTime }}分钟</span>
                  <span class="plan-type">{{ plan.type }}</span>
                </div>
              </div>
              <div class="plan-actions">
                <el-button size="small" @click="startPlan(plan)">
                  开始
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容 -->
      <div class="main-right">
        <!-- 学习日历 -->
        <div class="dashboard-card">
          <div class="card-header">
            <h3>学习日历</h3>
          </div>
          <div class="calendar-container">
            <el-calendar v-model="calendarDate" class="learning-calendar">
              <template #date-cell="{ data }">
                <div class="calendar-day" :class="getCalendarDayClass(data.day)">
                  <span class="day-number">{{ data.day.split('-').pop() }}</span>
                  <div v-if="hasLearningRecord(data.day)" class="learning-dot"></div>
                </div>
              </template>
            </el-calendar>
          </div>
        </div>

        <!-- 成就徽章 -->
        <div class="dashboard-card">
          <div class="card-header">
            <h3>最新成就</h3>
            <el-button text @click="viewAllAchievements">查看全部</el-button>
          </div>
          <div class="achievements-grid">
            <div 
              v-for="achievement in recentAchievements" 
              :key="achievement.id"
              class="achievement-item"
              :class="{ unlocked: achievement.unlocked }"
            >
              <div class="achievement-icon">
                <img :src="achievement.icon" :alt="achievement.name" />
              </div>
              <div class="achievement-info">
                <div class="achievement-name">{{ achievement.name }}</div>
                <div class="achievement-desc">{{ achievement.description }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 学习动态 -->
        <div class="dashboard-card">
          <div class="card-header">
            <h3>学习动态</h3>
          </div>
          <div class="activity-timeline">
            <div 
              v-for="activity in recentActivities" 
              :key="activity.id"
              class="activity-item"
            >
              <div class="activity-time">{{ formatActivityTime(activity.timestamp) }}</div>
              <div class="activity-content">
                <el-icon class="activity-icon">
                  <component :is="getActivityIcon(activity.type)" />
                </el-icon>
                <span>{{ activity.description }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { 
  VideoPlay, EditPen, Monitor, Sunny, Reading, Document, 
  Trophy, Medal, TrendCharts
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const currentDate = ref('')
const currentTime = ref('')
const calendarDate = ref(new Date())
const consecutiveDays = ref(15)

const learningStats = reactive({
  totalHours: 128,
  completedCourses: 12,
  examScore: 85,
  ranking: 156
})

const currentCourses = ref([
  {
    id: 1,
    title: 'Vue3 + TypeScript 实战开发',
    instructor: '张老师',
    cover: '/images/course-1.jpg',
    progress: 75
  },
  {
    id: 2,
    title: 'Node.js 后端开发',
    instructor: '李老师',
    cover: '/images/course-2.jpg',
    progress: 45
  },
  {
    id: 3,
    title: 'React 企业级应用开发',
    instructor: '王老师',
    cover: '/images/course-3.jpg',
    progress: 20
  }
])

const todayPlans = ref([
  {
    id: 1,
    title: '完成Vue3组件开发章节',
    type: '视频学习',
    estimatedTime: 45,
    completed: false
  },
  {
    id: 2,
    title: '练习JavaScript算法题',
    type: '编程练习',
    estimatedTime: 30,
    completed: true
  },
  {
    id: 3,
    title: '复习CSS布局知识点',
    type: '知识复习',
    estimatedTime: 20,
    completed: false
  }
])

const recentAchievements = ref([
  {
    id: 1,
    name: '学习达人',
    description: '连续学习7天',
    icon: '/images/achievement-1.png',
    unlocked: true
  },
  {
    id: 2,
    name: '编程新手',
    description: '完成第一个编程练习',
    icon: '/images/achievement-2.png',
    unlocked: true
  },
  {
    id: 3,
    name: '考试高手',
    description: '考试成绩达到90分',
    icon: '/images/achievement-3.png',
    unlocked: false
  }
])

const recentActivities = ref([
  {
    id: 1,
    type: 'course',
    description: '完成了《Vue3组件通信》课程',
    timestamp: new Date(Date.now() - 1000 * 60 * 30)
  },
  {
    id: 2,
    type: 'exam',
    description: '参加了《JavaScript基础》考试，得分88分',
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2)
  },
  {
    id: 3,
    type: 'achievement',
    description: '获得了"学习达人"徽章',
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 4)
  }
])

// 计算属性和方法
const getGreeting = () => {
  const hour = new Date().getHours()
  if (hour < 6) return '夜深了'
  if (hour < 9) return '早上好'
  if (hour < 12) return '上午好'
  if (hour < 14) return '中午好'
  if (hour < 18) return '下午好'
  if (hour < 22) return '晚上好'
  return '夜深了'
}

const updateTime = () => {
  const now = new Date()
  currentDate.value = now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getCalendarDayClass = (day) => {
  const today = new Date().toISOString().split('T')[0]
  if (day === today) return 'today'
  if (hasLearningRecord(day)) return 'has-learning'
  return ''
}

const hasLearningRecord = (day) => {
  // 模拟学习记录
  const learningDays = ['2024-01-10', '2024-01-11', '2024-01-12', '2024-01-14', '2024-01-15']
  return learningDays.includes(day)
}

const formatActivityTime = (timestamp) => {
  const now = new Date()
  const time = new Date(timestamp)
  const diff = now - time
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  return time.toLocaleDateString('zh-CN')
}

const getActivityIcon = (type) => {
  const iconMap = {
    course: VideoPlay,
    exam: EditPen,
    achievement: Trophy,
    coding: Monitor
  }
  return iconMap[type] || Document
}

// 事件处理
const goToLearning = () => {
  router.push('/classroom')
}

const goToExam = () => {
  router.push('/exam')
}

const goToCoding = () => {
  router.push('/coding')
}

const continueCourse = (course) => {
  router.push(`/classroom/course/${course.id}`)
}

const viewAllProgress = () => {
  router.push('/classroom/my-courses')
}

const managePlans = () => {
  router.push('/task/plans')
}

const updatePlanStatus = (plan) => {
  // 更新计划状态
  console.log('Plan status updated:', plan)
}

const startPlan = (plan) => {
  // 开始执行计划
  console.log('Start plan:', plan)
}

const viewAllAchievements = () => {
  router.push('/dashboard/achievements')
}

// 生命周期
onMounted(() => {
  updateTime()
  const timer = setInterval(updateTime, 60000) // 每分钟更新一次时间
  
  onUnmounted(() => {
    clearInterval(timer)
  })
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 20px;
  }
}

.welcome-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-avatar {
  position: relative;
  
  .online-status {
    position: absolute;
    bottom: 5px;
    right: 5px;
    width: 16px;
    height: 16px;
    background: #52c41a;
    border: 2px solid white;
    border-radius: 50%;
  }
}

.welcome-content {
  h1 {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 8px;
  }
  
  p {
    font-size: 16px;
    opacity: 0.9;
    margin-bottom: 20px;
  }
}

.quick-actions {
  display: flex;
  gap: 12px;
  
  .el-button {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
    
    &:hover {
      background: rgba(255, 255, 255, 0.3);
    }
  }
}

.weather-widget {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 16px;
}

.weather-info {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .weather-icon {
    font-size: 32px;
  }
  
  .temperature {
    font-size: 24px;
    font-weight: 600;
  }
  
  .weather-desc {
    font-size: 14px;
    opacity: 0.8;
  }
}

.date-info {
  text-align: right;
  
  .date {
    font-size: 16px;
    margin-bottom: 4px;
  }
  
  .time {
    font-size: 24px;
    font-weight: 600;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  }
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .el-icon {
    font-size: 28px;
    color: white;
  }
  
  &.study {
    background: linear-gradient(135deg, #667eea, #764ba2);
  }
  
  &.course {
    background: linear-gradient(135deg, #f093fb, #f5576c);
  }
  
  &.exam {
    background: linear-gradient(135deg, #4facfe, #00f2fe);
  }
  
  &.rank {
    background: linear-gradient(135deg, #43e97b, #38f9d7);
  }
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  
  &.up {
    color: var(--el-color-success);
  }
  
  &.down {
    color: var(--el-color-danger);
  }
}

.dashboard-main {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  
  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
  }
}

.dashboard-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    margin: 0;
  }
}

.progress-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.course-cover {
  position: relative;
  width: 80px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .play-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    
    .el-icon {
      color: white;
      font-size: 20px;
    }
  }
  
  .progress-item:hover & .play-overlay {
    opacity: 1;
  }
}

.course-info {
  flex: 1;
  
  h4 {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 4px;
  }
  
  p {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    margin-bottom: 8px;
  }
}

.progress-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .el-progress {
    flex: 1;
  }
  
  .progress-text {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-color-primary);
  }
}

.plan-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.plan-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  transition: all 0.3s ease;
  
  &.completed {
    opacity: 0.6;
    
    .plan-title {
      text-decoration: line-through;
    }
  }
  
  &:hover {
    background: var(--el-fill-color-extra-light);
  }
}

.plan-content {
  flex: 1;
}

.plan-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.plan-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.learning-calendar {
  :deep(.el-calendar__body) {
    padding: 12px;
  }
  
  :deep(.el-calendar-table .el-calendar-day) {
    padding: 0;
  }
}

.calendar-day {
  position: relative;
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.3s ease;
  
  &.today {
    background: var(--el-color-primary);
    color: white;
  }
  
  &.has-learning {
    background: var(--el-color-success-light-9);
    color: var(--el-color-success);
  }
  
  .learning-dot {
    position: absolute;
    bottom: 4px;
    right: 4px;
    width: 6px;
    height: 6px;
    background: var(--el-color-success);
    border-radius: 50%;
  }
}

.achievements-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.achievement-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  opacity: 0.5;
  
  &.unlocked {
    opacity: 1;
    background: var(--el-color-success-light-9);
    border-color: var(--el-color-success-light-7);
  }
}

.achievement-icon {
  width: 40px;
  height: 40px;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.achievement-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
}

.achievement-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.activity-timeline {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.activity-time {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  white-space: nowrap;
  margin-top: 2px;
}

.activity-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  
  .activity-icon {
    color: var(--el-color-primary);
  }
}
</style>
